<template>
  <div class="files-list">
    <div class="container">
      <div class="file-container">
        <div class="file-header">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部" name="0"></el-tab-pane>
            <el-tab-pane label="图片" name="1"></el-tab-pane>
            <el-tab-pane label="视频" name="2"></el-tab-pane>
            <el-tab-pane label="文档" name="3"></el-tab-pane>
            <el-tab-pane label="压缩包" name="4"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="file-item">
          <!-- 分组 -->
          <div class="group">
            <ul id="group" class="groups">
              <li :class="{ active: activeGroup === '' }" @click="selectGroup('')" data-id="">
                <i class="iconfont icon-sucaiziyuan"></i>
                <span>全部</span>
              </li>
              <li :class="{ active: activeGroup === '0' }" @click="selectGroup('0')" data-id="0">
                <i class="iconfont icon-sucaiziyuan"></i>
                <span>未分组</span>
              </li>
              <li
                v-for="group in fileGroups"
                :key="group.id"
                :class="{ active: activeGroup === String(group.id) }"
                @click="selectGroup(String(group.id))"
                :data-id="group.id"
              >
                <i class="iconfont icon-sucaiziyuan"></i>
                <span>{{ group.title }}</span>
                <div class="group-actions">
                  <el-dropdown @command="handleGroupCommand">
                    <i class="layui-icon layui-icon-more-vertical dropdown-on"></i>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{ action: 'rename', data: group }">
                          重命名分组
                        </el-dropdown-item>
                        <el-dropdown-item :command="{ action: 'delete', data: group }">
                          删除该分组
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </li>
            </ul>
            <div class="footer">
              <el-button type="primary" size="small" @click="addGroup">添加分组</el-button>
            </div>
          </div>
          <!-- 文件 -->
          <div class="attach">
            <!-- 工具 -->
            <div class="header">
              <div class="layui-btn-group">
                <el-button type="primary" size="small" @click="uploadFile">上传文件</el-button>
                <el-button type="danger" size="small" @click="deleteSelectedFiles">
                  批量删除
                </el-button>
                <el-dropdown @command="moveFiles">
                  <el-button type="warning" size="small">
                    移动至
                    <i class="layui-icon layui-icon-triangle-d"></i>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        v-for="group in fileGroups"
                        :key="group.id"
                        :command="group.id"
                      >
                        {{ group.title }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <span style="margin-left: 36px">
                  <el-checkbox v-model="selectAll" @change="handleSelectAllChange">
                    全选
                  </el-checkbox>
                </span>
              </div>

              <div class="search">
                <input type="hidden" name="limit" v-model="searchForm.limit" />
                <input type="hidden" name="page" v-model="searchForm.page" />
                <input type="hidden" name="tab" v-model="searchForm.tab" />
                <input type="hidden" name="group_id" v-model="searchForm.group_id" />
                <div class="search-input">
                  <el-input
                    v-model="searchForm.keywords"
                    placeholder="请输入名称"
                    style="width: 200px"
                  />
                  <el-button type="primary" @click="searchFiles">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
            <!-- 主体 -->
            <div class="subject">
              <ul id="filesBox" v-loading="loading">
                <li
                  v-for="file in fileList"
                  :key="file.id"
                  :class="{ on: selectedFiles.includes(file.id) }"
                  :data-id="file.id"
                  :data-title="file.name"
                  :data-ext="file.fileext"
                >
                  <img
                    :src="getFileIcon(file)"
                    :alt="file.name"
                    style="object-fit: contain"
                    class="file-items"
                    :class="'file-' + getFileType(file.fileext)"
                    @click="viewFile(file)"
                    @error="event => handleImageError(event, file)"
                  />
                  <p :title="file.name">{{ file.name }}</p>
                  <div class="layui-btn-ctrl">
                    <el-button type="primary" size="small" @click="viewFile(file)">查看</el-button>
                    <el-dropdown @command="handleFileCommand">
                      <el-button size="small">
                        <el-icon><ArrowDown /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="{ action: 'rename', data: file }">
                            重命名
                          </el-dropdown-item>
                          <el-dropdown-item :command="{ action: 'delete', data: file }">
                            删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                  <div class="file-check" @click="toggleFileSelection(file.id)">✔</div>
                </li>
                <div v-if="fileList.length === 0" class="empty">
                  <i class="layui-icon layui-icon-upload"></i>
                  <p>无文件文件，赶紧去上传吧!</p>
                </div>
              </ul>
            </div>
            <!-- 页脚 -->
            <div class="footer">
              <el-pagination
                v-model:current-page="searchForm.page"
                v-model:page-size="searchForm.limit"
                :page-sizes="[20, 44, 88, 176]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传文件" width="500px">
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持格式: jpeg|jpg|png|gif|doc|docx|ppt|pptx|xls|xlsx|pdf|zip|rar|7z|txt|mp4|psd|svg
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="previewFile.name"
      width="80%"
      top="50px"
      :before-close="handlePreviewClose"
    >
      <div class="file-preview-container">
        <!-- 图片预览 -->
        <div v-if="isPreviewImage" class="image-preview">
          <img :src="previewFileUrl" alt="预览图片" class="preview-image" />
        </div>

        <!-- PDF预览 -->
        <div v-else-if="isPreviewPdf" class="pdf-preview">
          <iframe :src="previewFileUrl" class="preview-iframe" frameborder="0"></iframe>
        </div>

        <!-- 视频预览 -->
        <div v-else-if="isPreviewVideo" class="video-preview">
          <video :src="previewFileUrl" controls class="preview-video"></video>
        </div>

        <!-- 文本文档预览 -->
        <div v-else-if="isPreviewText" class="text-preview">
          <iframe :src="previewFileUrl" class="preview-iframe" frameborder="0"></iframe>
        </div>

        <!-- 其他文件类型 -->
        <div v-else class="other-preview">
          <div class="file-info">
            <p>文件名: {{ previewFile.name }}</p>
            <p>文件大小: {{ formatFileSize(previewFile.filesize) }}</p>
            <p>文件类型: {{ previewFile.fileext }}</p>
            <el-button type="primary" @click="downloadFile">下载文件</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, ArrowDown, UploadFilled } from '@element-plus/icons-vue'
  import {
    getFileList as getFileListApi,
    updateFile as updateFileApi,
    deleteFile as deleteFileApi,
  } from '@/api/home/files'

  // 数据相关
  const activeTab = ref('0')
  const activeGroup = ref('')
  const selectAll = ref(false)
  const selectedFiles = ref<number[]>([])
  const loading = ref(false)

  // 文件相关
  const fileList = ref<any[]>([])
  const fileGroups = ref<any[]>([])
  const total = ref(0)

  // 搜索表单
  const searchForm = reactive({
    limit: 44,
    page: 1,
    tab: '0',
    group_id: '',
    keywords: '',
  })

  // 上传相关
  const uploadDialogVisible = ref(false)
  const uploadUrl = ref(import.meta.env.VITE_API_BASE_URL + '/api/home/files/save')
  const uploadHeaders = ref({
    Authorization: 'Bearer ' + localStorage.getItem('token'),
  })

  // 文件预览相关
  const previewDialogVisible = ref(false)
  const previewFile = ref<any>({})
  const previewFileUrl = ref('')

  // 计算属性：判断文件类型
  const isPreviewImage = computed(() => {
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']
    return imageTypes.includes(previewFile.value.fileext?.toLowerCase() || '')
  })

  const isPreviewPdf = computed(() => {
    return (previewFile.value.fileext?.toLowerCase() || '') === 'pdf'
  })

  const isPreviewVideo = computed(() => {
    const videoTypes = ['mp4', 'webm', 'ogg', 'avi', 'mov', 'wmv']
    return videoTypes.includes(previewFile.value.fileext?.toLowerCase() || '')
  })

  const isPreviewText = computed(() => {
    const textTypes = ['txt', 'md', 'html', 'htm']
    return textTypes.includes(previewFile.value.fileext?.toLowerCase() || '')
  })

  // 获取文件列表
  const getFiles = async () => {
    try {
      loading.value = true
      const response: any = await getFileListApi(searchForm)

      if (response.code === 0) {
        // 检查响应数据的结构
        if (response.data && Array.isArray(response.data.data)) {
          // 有分页数据结构
          fileList.value = response.data.data
          total.value = response.data.total || 0
        } else if (Array.isArray(response.data)) {
          // 直接是数组
          fileList.value = response.data
          total.value = response.count || 0
        } else {
          console.warn('File list data format is incorrect:', response.data)
          fileList.value = []
          total.value = 0
        }
      } else {
        ElMessage.error(response.msg || '获取文件列表失败')
        fileList.value = []
        total.value = 0
      }
    } catch (error) {
      console.error('Failed to fetch file list:', error)
      ElMessage.error('获取文件列表失败: ' + ((error as any).message || '未知错误'))
      fileList.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 获取分组列表
  const getGroups = async () => {
    try {
      // 由于后端没有提供专门的获取分组列表的接口，我们暂时使用静态数据
      // 后续可以根据实际需求添加分组功能
      fileGroups.value = [
        { id: 1, title: '图片' },
        { id: 2, title: '文档' },
        { id: 3, title: '视频' },
        { id: 4, title: '其他' },
      ]
    } catch (error) {
      console.error('Failed to fetch file groups:', error)
      ElMessage.error('获取分组列表失败: ' + ((error as any).message || '未知错误'))
      fileGroups.value = []
    }
  }

  // 处理标签页切换
  const handleTabChange = (name: string) => {
    searchForm.tab = name
    searchForm.page = 1
    getFiles()
  }

  // 选择分组
  const selectGroup = (groupId: string) => {
    activeGroup.value = groupId
    searchForm.group_id = groupId
    searchForm.page = 1
    getFiles()
  }

  // 处理全选变化
  const handleSelectAllChange = (val: boolean) => {
    if (val) {
      selectedFiles.value = fileList.value.map(file => file.id)
    } else {
      selectedFiles.value = []
    }
  }

  // 切换文件选择
  const toggleFileSelection = (id: number) => {
    const index = selectedFiles.value.indexOf(id)
    if (index === -1) {
      selectedFiles.value.push(id)
    } else {
      selectedFiles.value.splice(index, 1)
    }
  }

  // 上传文件
  const uploadFile = () => {
    uploadDialogVisible.value = true
  }

  // 处理上传成功
  const handleUploadSuccess = (response: any) => {
    ElMessage.success(response.msg || '上传成功')
    uploadDialogVisible.value = false
    getFiles()
  }

  // 处理上传失败
  const handleUploadError = (_error: any) => {
    ElMessage.error('上传失败')
  }

  // 删除选中文件
  const deleteSelectedFiles = () => {
    if (selectedFiles.value.length === 0) {
      ElMessage.warning('请先选择文件')
      return
    }

    ElMessageBox.confirm('确定要删除这些文件吗？请慎重', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        const response: any = await deleteFileApi(selectedFiles.value.join(','))

        ElMessage.success(response.msg || '删除成功')
        getFiles()
        selectedFiles.value = []
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
  }

  // 移动文件
  const moveFiles = async (groupId: number) => {
    ElMessage.warning('移动文件功能暂未实现')
    // if (selectedFiles.value.length === 0) {
    //   ElMessage.warning('请先选择文件')
    //   return
    // }

    // 获取分组名称
    // const group = fileGroups.value.find((g: any) => g.id === groupId)
    // const groupName = group ? group.title : '未分组'

    // ElMessageBox.confirm(`确定要把选中的文件移动到『${groupName}』分组吗？`, '提示', {
    //   confirmButtonText: '确定',
    //   cancelButtonText: '取消',
    //   type: 'warning'
    // }).then(async () => {
    //   try {
    //     const response: any = await moveFileApi({
    //       group_id: groupId,
    //       ids: selectedFiles.value.join(',')
    //     })

    //     ElMessage.success(response.msg || '移动成功')
    //     getFiles()
    //     selectedFiles.value = []
    //   } catch (error) {
    //     ElMessage.error('移动失败')
    //   }
    // })
  }

  // 添加分组
  const addGroup = () => {
    ElMessage.warning('添加分组功能暂未实现')
    // ElMessageBox.prompt('请输入分组名称', '新增分组', {
    //   confirmButtonText: '确定',
    //   cancelButtonText: '取消'
    // }).then(async ({ value }) => {
    //   if (value) {
    //     try {
    //       const response: any = await addGroupApi({
    //         title: value
    //       })

    //       ElMessage.success(response.msg || '添加成功')
    //       getGroups()
    //     } catch (error) {
    //       ElMessage.error('添加失败')
    //     }
    //   } else {
    //     ElMessage.warning('请填写分组名称')
    //   }
    // }).catch(() => {
    //   // 取消操作
    // })
  }

  // 处理分组命令
  const handleGroupCommand = (command: any) => {
    ElMessage.warning('分组管理功能暂未实现')
    // const { action, data } = command
    // if (action === 'rename') {
    //   ElMessageBox.prompt('请输入分组名称', '重命名分组', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     inputValue: data.title
    //   }).then(async ({ value }) => {
    //     if (value) {
    //       try {
    //         const response: any = await addGroupApi({
    //           id: data.id,
    //           title: value
    //         })

    //         ElMessage.success(response.msg || '重命名成功')
    //         getGroups()
    //       } catch (error) {
    //         ElMessage.error('重命名失败')
    //       }
    //     } else {
    //       ElMessage.warning('请填写分组名称')
    //     }
    //   }).catch(() => {
    //     // 取消操作
    //   })
    // } else if (action === 'delete') {
    //   ElMessageBox.confirm('确定要删除该分组吗？请慎重', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(async () => {
    //     try {
    //       const response: any = await deleteGroupApi(data.id)

    //       ElMessage.success(response.msg || '删除成功')
    //       getGroups()
    //     } catch (error) {
    //       ElMessage.error('删除失败')
    //     }
    //   })
    // }
  }

  // 处理文件命令
  const handleFileCommand = (command: any) => {
    const { action, data } = command
    if (action === 'rename') {
      ElMessageBox.prompt('请输入文件名称', '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: data.name.replace(/\.[^.]+$/, ''),
      })
        .then(async ({ value }) => {
          if (value) {
            try {
              const response: any = await updateFileApi({
                id: data.id,
                title: value + '.' + data.fileext,
              })

              ElMessage.success(response.msg || '重命名成功')
              getFiles()
            } catch (error) {
              ElMessage.error('重命名失败')
            }
          } else {
            ElMessage.warning('请填写文件名称')
          }
        })
        .catch(() => {
          // 取消操作
        })
    } else if (action === 'delete') {
      ElMessageBox.confirm('确定要删除该文件吗？请慎重', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          const response: any = await deleteFileApi(data.id)

          ElMessage.success(response.msg || '删除成功')
          getFiles()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }
  }

  // 处理文件操作
  const handleFileAction = (file: any) => {
    // 可以根据文件类型执行不同的操作
    ElMessage.info(`对文件 ${file.name} 执行操作`)
  }

  // 获取文件预览URL
  const getFilePreviewUrl = (file: any) => {
    let filePath = file.filepath
    // 处理原始文件路径

    // 检查是否为完整URL（http或https开头）
    if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
      // 检查是否完整URL
      return filePath
    }

    // 处理以/开头的绝对路径
    if (filePath.startsWith('/')) {
      // 检查是否是/storage开头的路径
      if (filePath.startsWith('/storage')) {
        // 使用API基础URL
        const baseUrl = import.meta.env.VITE_API_BASE_URL || window.location.origin
        const fullPath = baseUrl + filePath
        // 处理/storage绝对路径
        return fullPath
      } else {
        // 其他绝对路径使用当前域名
        const baseUrl = window.location.origin
        const fullPath = baseUrl + filePath
        // 处理其他绝对路径
        return fullPath
      }
    }

    // 处理相对路径
    const baseUrl = import.meta.env.VITE_API_BASE_URL || window.location.origin
    // 确保路径格式正确
    if (filePath.startsWith('./')) {
      filePath = filePath.substring(2)
    }

    const fullPath = baseUrl + '/' + filePath
    // 处理相对路径
    return fullPath
  }

  // 查看文件
  const viewFile = (file: any) => {
    // 查看文件处理
    // 设置预览文件
    previewFile.value = file

    // 获取文件预览URL
    const fileUrl = getFilePreviewUrl(file)
    previewFileUrl.value = fileUrl

    // 文件预览URL处理

    // 显示预览对话框
    previewDialogVisible.value = true
  }

  // 下载文件
  const downloadFile = () => {
    try {
      // 使用预览URL进行下载
      const link = document.createElement('a')
      link.href = previewFileUrl.value
      link.download = previewFile.value.name || 'download'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      ElMessage.success(`正在下载: ${previewFile.value.name}`)
    } catch (error) {
      console.error('Download error:', error)
      ElMessage.error(`下载失败: ${previewFile.value.name}`)
    }
  }

  // 格式化文件大小
  const formatFileSize = (size: number) => {
    if (size < 1024) {
      return size + ' B'
    } else if (size < 1024 * 1024) {
      return (size / 1024).toFixed(2) + ' KB'
    } else if (size < 1024 * 1024 * 1024) {
      return (size / (1024 * 1024)).toFixed(2) + ' MB'
    } else {
      return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
    }
  }

  // 获取文件图标
  const getFileIcon = (file: any) => {
    const extLower = file.fileext.toLowerCase()
    // 文件图标处理逻辑

    // 图片类型
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']

    // 可以直接显示的图片文件
    if (imageTypes.includes(extLower)) {
      // 如果是图片类型且有有效路径，则直接显示
      if (file.filepath) {
        try {
          // 处理路径
          let imagePath = file.filepath

          // 检查是否为完整URL
          if (imagePath.startsWith('http')) {
            // 已经是完整URL，直接返回
            // 返回完整URL图片路径
            return imagePath
          } else if (imagePath.startsWith('/')) {
            // 如果是以/开头的绝对路径，添加完整的域名
            const baseUrl = window.location.origin
            imagePath = baseUrl + imagePath
            // 处理绝对路径图片
          } else {
            // 如果是相对路径，添加基础URL
            // 修复：确保使用正确的API基础URL
            const baseUrl = import.meta.env.VITE_API_BASE_URL || window.location.origin
            // 确保路径格式正确
            if (imagePath.startsWith('./')) {
              imagePath = imagePath.substring(2)
            }
            imagePath = baseUrl + '/' + imagePath
            // 处理相对路径图片
          }

          // 确保返回有效的图片路径
          // 最终图片路径处理
          return imagePath || '/static/images/icon/img.png'
        } catch (error) {
          console.error('图片路径处理错误:', error)
          // 出错时返回默认图片图标
          return '/static/images/icon/img.png'
          // 无有效文件路径，返回默认图标
        }
      } else {
        // 如果没有有效的文件路径，返回默认图片图标
        console.log('无有效文件路径，返回默认图片图标')
        return '/static/images/icon/img.png'
      }
    }

    // 基于已有的图标文件列表匹配
    // 直接按文件后缀名查找图标
    const knownExtensions = [
      'jpg',
      'png',
      'gif',
      'svg', // 图片文件
      'doc',
      'docx',
      'ppt',
      'pptx',
      'xls',
      'xlsx',
      'pdf',
      'txt', // 办公文件
      'zip',
      'rar',
      '7z', // 压缩文件
      'mp4',
      'psd', // 其他文件
    ]

    // 如果有直接匹配的图标文件
    if (knownExtensions.includes(extLower)) {
      const iconPath = `/static/images/icon/${extLower}.png`
      // 返回匹配图标
      return iconPath
    }

    // 如果没有直接匹配，按类型匹配
    if (extLower === 'jpeg') {
      // 返回JPEG图标
      return '/static/images/icon/jpg.png'
    }
    if (['mp3', 'wav', 'ogg', 'flac', 'm4a'].includes(extLower)) {
      // 返回音频图标
      return '/static/images/icon/audio.png'
    }
    if (['avi', 'mov', 'wmv', 'flv', 'mkv'].includes(extLower)) {
      // 返回视频图标
      return '/static/images/icon/mp4.png'
    }
    if (['bmp', 'webp', 'tiff', 'ico'].includes(extLower)) {
      // 返回图片图标
      return '/static/images/icon/img.png'
    }

    // 最后返回默认图标
    // 返回默认文件图标
    return '/static/images/icon/file.png'
  }

  // 添加图片加载错误处理函数
  const handleImageError = (event: any, file: any) => {
    console.error('图片加载失败:', file.name, event.target.src)
    // 检查是否已经是图标路径，避免无限循环
    const currentSrc = event.target.src
    if (!currentSrc.includes('/static/images/icon/')) {
      // 设置默认图标
      event.target.src = '/static/images/icon/file.png'
    }
  }

  // 获取文件类型
  const getFileType = (ext: string) => {
    const extLower = ext.toLowerCase()

    // 图片类型
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'bmp', 'webp']

    // 办公文件类型
    const docTypes = ['doc', 'docx']
    const excelTypes = ['xls', 'xlsx']
    const pptTypes = ['ppt', 'pptx']
    const pdfTypes = ['pdf']
    const textTypes = ['txt', 'md', 'rtf']

    // 压缩文件类型
    const archiveTypes = ['zip', 'rar', '7z', 'tar', 'gz']

    // 音视频类型
    const audioTypes = ['mp3', 'wav', 'ogg', 'flac', 'm4a']
    const videoTypes = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv']

    // 设计和代码文件
    const designTypes = ['psd', 'ai', 'sketch']

    if (imageTypes.includes(extLower)) {
      return 'image'
    }

    if (docTypes.includes(extLower)) {
      return 'doc'
    }

    if (excelTypes.includes(extLower)) {
      return 'excel'
    }

    if (pptTypes.includes(extLower)) {
      return 'ppt'
    }

    if (pdfTypes.includes(extLower)) {
      return 'pdf'
    }

    if (textTypes.includes(extLower)) {
      return 'text'
    }

    if (archiveTypes.includes(extLower)) {
      return 'archive'
    }

    if (audioTypes.includes(extLower)) {
      return 'audio'
    }

    if (videoTypes.includes(extLower)) {
      return 'video'
    }

    if (designTypes.includes(extLower)) {
      return 'design'
    }

    return 'file'
  }

  // 搜索文件
  const searchFiles = () => {
    searchForm.page = 1
    getFiles()
  }

  // 处理分页大小变化
  const handleSizeChange = (val: number) => {
    searchForm.limit = val
    searchForm.page = 1
    getFiles()
  }

  // 处理当前页变化
  const handleCurrentChange = (val: number) => {
    searchForm.page = val
    getFiles()
  }

  // 关闭预览对话框
  const handlePreviewClose = () => {
    previewDialogVisible.value = false
    previewFile.value = {}
    previewFileUrl.value = ''
    return true
  }

  // 初始化
  onMounted(() => {
    getFiles()
    getGroups()
  })
</script>

<style scoped>
  .files-list {
    height: 100%;
    display: flex;
    overflow: hidden;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f4 100%);
    padding: 20px;
  }

  .container {
    display: flex;
    flex: 1;
    flex-direction: column;
    overflow: hidden;
    border-radius: 12px;
    background: #ffffff;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
    height: calc(100vh - 40px);
  }

  .file-container {
    display: flex;
    flex: 1;
    flex-direction: column;
    overflow: hidden;
    border-radius: 12px;
    background: #ffffff;
  }

  .file-item {
    display: flex;
    flex: 1;
    justify-content: space-between;
    overflow: hidden;
  }

  .file-header {
    padding: 0 20px;
    border-bottom: 1px solid #ebeef5;
  }

  .file-header :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  .file-header :deep(.el-tabs__nav-wrap)::after {
    display: none;
  }

  .file-header :deep(.el-tabs__item) {
    height: 50px;
    line-height: 50px;
    font-size: 15px;
    font-weight: 500;
    color: #606266;
  }

  .file-header :deep(.el-tabs__item.is-active) {
    color: #409eff;
    font-weight: 600;
  }

  /** 分组 **/
  .group {
    position: relative;
    display: flex;
    flex-direction: column;
    width: 240px;
    border-right: 1px solid #ebeef5;
    background: linear-gradient(180deg, #fafbff 0%, #f5f7fa 100%);
    box-shadow: 2px 0 10px rgba(0, 0, 0, 0.03);
    z-index: 1;
  }

  .group ul {
    flex: 1;
    overflow: hidden;
    overflow-y: auto;
    padding: 15px 0;
  }

  .group ul li {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 12px 20px;
    margin: 0 15px;
    border-radius: 8px;
    font-size: 14px;
    color: #606266;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
  }

  .group ul li i.iconfont {
    margin-right: 12px;
    font-size: 18px;
    color: #79bbff;
    transition: all 0.3s ease;
  }

  .group ul li > span {
    display: flex;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-weight: 500;
  }

  .group ul li.active {
    background: linear-gradient(90deg, #409eff 0%, #79bbff 100%);
    color: #ffffff;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }

  .group ul li.active i.iconfont {
    color: #ffffff;
  }

  .group ul li:hover:not(.active) {
    background-color: #f0f5ff;
    color: #409eff;
  }

  .group ul li:hover:not(.active) i.iconfont {
    color: #409eff;
    transform: scale(1.1);
  }

  .group ul li .group-actions {
    display: none;
    position: absolute;
    right: 15px;
    top: 50%;
    transform: translateY(-50%);
  }

  .group ul li:hover .group-actions {
    display: block;
  }

  .group ul li .group-actions :deep(.el-dropdown) {
    color: #909399;
  }

  .group ul li.active .group-actions :deep(.el-dropdown) {
    color: #ffffff;
  }

  .group .footer {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding: 20px 0;
    border-top: 1px solid #ebeef5;
    background: #ffffff;
  }

  .group .footer :deep(.el-button) {
    width: 80%;
    border-radius: 20px;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  }

  /** 文件 **/
  .attach {
    position: relative;
    display: flex;
    flex: 1;
    flex-direction: column;
    background: #ffffff;
  }

  .attach .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    background: #ffffff;
  }

  .attach .header .layui-btn-group {
    display: flex;
    gap: 12px;
  }

  .attach .header .layui-btn-group :deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
  }

  .attach .header .layui-btn-group :deep(.el-button:hover) {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  }

  .attach .header .layui-btn-group :deep(.el-button--primary) {
    background: linear-gradient(135deg, #409eff 0%, #79bbff 100%);
    border: none;
  }

  .attach .header .layui-btn-group :deep(.el-button--danger) {
    background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
    border: none;
  }

  .attach .header .layui-btn-group :deep(.el-button--warning) {
    background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
    border: none;
  }

  .attach .header .search {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .attach .header .search :deep(.el-input__wrapper) {
    border-radius: 20px;
  }

  .attach .header .search :deep(.el-button) {
    border-radius: 20px;
    padding: 8px 20px;
    background: linear-gradient(135deg, #409eff 0%, #79bbff 100%);
    border: none;
    color: white;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  }

  .attach .subject {
    flex: 1;
    overflow: hidden;
    overflow-y: auto;
    padding: 20px;
    background: #f8f9fc;
  }

  .attach .subject ul {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 20px;
    padding: 0;
    margin: 0;
  }

  .attach .subject ul li {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    padding: 15px;
    border-radius: 12px;
    background: #ffffff;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
    transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
    overflow: hidden;
    cursor: pointer;
    border: 2px solid transparent;
  }

  .attach .subject ul li:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 25px rgba(0, 0, 0, 0.12);
    border-color: #79bbff;
  }

  .attach .subject ul li.on {
    border-color: #409eff;
    background: linear-gradient(135deg, rgba(64, 158, 255, 0.05) 0%, rgba(121, 187, 255, 0.1) 100%);
    box-shadow: 0 6px 20px rgba(64, 158, 255, 0.2);
  }

  .attach .subject ul li img {
    width: 80px;
    height: 80px;
    object-fit: contain;
    margin-bottom: 15px;
    transition: all 0.3s ease;
    border-radius: 6px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  }

  .attach .subject ul li:hover img {
    transform: scale(1.05);
  }

  .attach .subject ul li img.file-image {
    width: 100%;
    height: 120px;
    object-fit: cover;
    border-radius: 8px;
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
  }

  .attach .subject ul li p {
    width: 100%;
    font-size: 13px;
    font-weight: 500;
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
    color: #606266;
    padding: 0 5px;
  }

  .attach .subject ul li:hover p {
    color: #409eff;
  }

  .attach .subject ul li.on p {
    color: #409eff;
    font-weight: 600;
  }

  .attach .subject ul li .file-check {
    position: absolute;
    width: 26px;
    height: 26px;
    left: 12px;
    top: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    border-radius: 50%;
    color: #ffffff;
    background-color: #dcdfe6;
    border: 2px solid #ffffff;
    cursor: pointer;
    z-index: 10;
    transition: all 0.2s ease;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    opacity: 0;
    transform: scale(0.8);
  }

  .attach .subject ul li:hover .file-check,
  .attach .subject ul li.on .file-check {
    opacity: 1;
    transform: scale(1);
  }

  .attach .subject ul li.on .file-check {
    background: #409eff;
    border-color: #ffffff;
    box-shadow: 0 3px 8px rgba(64, 158, 255, 0.4);
  }

  .attach .subject ul li .layui-btn-ctrl {
    position: absolute;
    top: 12px;
    right: 12px;
    display: flex;
    gap: 5px;
    z-index: 10;
    opacity: 0;
    transform: translateY(-10px);
    transition: all 0.3s ease;
  }

  .attach .subject ul li:hover .layui-btn-ctrl {
    opacity: 1;
    transform: translateY(0);
  }

  .attach .subject ul li .layui-btn-ctrl :deep(.el-button) {
    padding: 6px;
    border-radius: 6px;
    min-height: auto;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }

  .attach .subject ul li .layui-btn-ctrl :deep(.el-button--primary) {
    background: #409eff;
    border-color: #409eff;
    color: white;
  }

  .attach .subject ul li .layui-btn-ctrl :deep(.el-button:hover) {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  }

  .attach .footer {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    border-top: 1px solid #ebeef5;
    background: #ffffff;
  }

  .attach .footer :deep(.el-pagination) {
    padding: 0;
  }

  .attach .footer :deep(.el-pagination .el-pager li) {
    border-radius: 6px;
    margin: 0 2px;
  }

  .attach .footer :deep(.el-pagination .btn-prev),
  .attach .footer :deep(.el-pagination .btn-next) {
    border-radius: 6px;
  }

  .attach .footer :deep(.el-pagination .el-input__wrapper) {
    border-radius: 6px;
  }

  /** 无数据 **/
  .empty {
    display: flex;
    flex: 1;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
    text-align: center;
    color: #c0c4cc;
    padding: 40px;
    background: #f8f9fc;
    border-radius: 12px;
    margin: 20px;
  }

  .empty i {
    font-size: 120px;
    margin-bottom: 20px;
    color: #dcdfe6;
  }

  .empty p {
    font-size: 16px;
    color: #909399;
    margin: 0;
  }

  /** 上传对话框 **/
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #409eff 0%, #79bbff 100%);
    color: white;
    padding: 20px;
  }

  :deep(.el-dialog__title) {
    color: white;
    font-weight: 500;
  }

  :deep(.el-dialog__headerbtn .el-dialog__close) {
    color: white;
  }

  :deep(.el-upload) {
    width: 100%;
  }

  :deep(.el-upload-dragger) {
    width: 100%;
    border-radius: 12px;
    border: 2px dashed #c0c4cc;
    transition: all 0.3s ease;
  }

  :deep(.el-upload-dragger:hover) {
    border-color: #409eff;
    background-color: rgba(64, 158, 255, 0.05);
  }

  :deep(.el-upload-dragger.is-dragover) {
    border-color: #409eff;
    background-color: rgba(64, 158, 255, 0.1);
  }

  :deep(.el-icon--upload) {
    font-size: 60px;
    color: #c0c4cc;
    margin-bottom: 15px;
  }

  :deep(.el-upload__text) {
    font-size: 16px;
    color: #606266;
    margin-bottom: 15px;
  }

  :deep(.el-upload__text em) {
    color: #409eff;
    font-weight: 600;
    font-style: normal;
  }

  :deep(.el-upload__tip) {
    font-size: 13px;
    color: #909399;
    text-align: center;
  }
</style>
